from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from .libs.captcha.captcha import captcha
from django import http
# Create your views here.
class ImageCodeView(View):
    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpg
        """
        # 获取到验证码的文字和图片
        text, img = captcha.generate_captcha()
        # 与ｒｅｄｉｓ数据库交互
        redis_conn = get_redis_connection('verify_code')
        # 设置过期时间３００秒
        redis_conn.setex('img_%s' % uuid, 300, text)
        return http.HttpResponse(img, content_type='image/jpg')

class CheckImageCodeView(View):
    def get(self,request):
        uuid = request.GET.get('uuid')
        image_code = request.GET.get('image_code')
        redis_conn = get_redis_connection('verify_code')
        image_code_server = redis_conn.get('img_%s' % uuid)
        print(image_code_server)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            print('图片过期')
            return http.JsonResponse({'code': '1', 'errmsg': '图形验证码失效'})
        # 比较验证码
        image_code_server = image_code_server.decode()  # bytes转字符串
        if image_code.lower() != image_code_server.lower():  # 转小写后比较
            print('图片错误')
            return http.JsonResponse({'code': '1', 'errmsg': '输入图形验证码有误'})
        else:
            return http.JsonResponse({'code': '0', 'errmsg': '输入图形验证码有误'})



